package com.stockz.core.dao;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.PersistenceUnit;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.jpa.EntityManagerFactoryInfo;
import org.springframework.stereotype.Component;

import com.stockz.downloaderx.DownloadManager;

@Component
public class JpaUtil{

	@PersistenceUnit
	@Autowired
	private EntityManagerFactory entityManagerFactory;
	
	
	public void shutdownDatabase(){
		DownloadManager.lock();
		EntityManager em = entityManagerFactory.createEntityManager();
		EntityTransaction transaction = em.getTransaction();
		transaction.begin();
		em.createNativeQuery("shutdown").executeUpdate();
		//Database will be shutdown thus no need to commit the transaction
	}
	
	
	
	 public DataSource getDataSource(){
	        if (entityManagerFactory instanceof EntityManagerFactoryInfo) {
	            EntityManagerFactoryInfo emfInfo = (EntityManagerFactoryInfo)entityManagerFactory;
	            return emfInfo.getDataSource();
	        }
	        return null;
	    }
	
}
